package com.example.common;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.entity.User;
import com.example.exception.CustomerException;
import com.example.service.LoginService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Enumeration;

@Component
// 拦截器实现，对token进行拦截并解析，看看是不是合法的token
public class JWTInterceptor implements HandlerInterceptor {
    @Resource
    LoginService loginService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        String uri = request.getRequestURI();
        System.out.println("uri=====>"+uri);
        if (uri.equals("//login") || uri.equals("/register") || uri.equals("/captcha")) {
            return true;
        }
        // 1. 从请求头拿到token
        String token = request.getHeader("token");
        Enumeration<String> headerNames = request.getHeaderNames();
        if (StrUtil.isEmpty(token)) {
            // 如果没拿到，从参数里再拿一次
            token = request.getParameter("token");
        }
        // 2. 认证token
        if (StrUtil.isBlank(token)) {
            throw new CustomerException(403, "您无权限操作");
        }
        User user = null;
        try {
            // 拿到token 的载荷数据
            String audience = JWT.decode(token).getAudience().get(0);
            System.out.println("vaudience=====>"+audience);
            String[] split = audience.split("-");
            String comPartyId = split[0];
            String roleId = request.getHeader("roleId");
            request.setAttribute("comPartyId", roleId);
//            request.setAttribute("comPartyId", comPartyId);
            String userId = split[1];
            request.setAttribute("userId", userId);
            String saler = split[2];
            request.setAttribute("saler", saler);
            // 根据token解析出来的userId去对应的表查询用户信息
            user = loginService.selectById(userId);
        } catch (Exception e) {
            throw new CustomerException(403, "您无权限操作");
        }
        if (user == null) {
            throw new CustomerException(403, "您无权限操作");
        }
        try {
            // 验证签名
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassWord())).build();
            jwtVerifier.verify(token);
        } catch (Exception e) {
            throw new CustomerException(401, "登录已过期");
        }
        return true;
    }
}
